package com.ioc;

import com.ioc.annotation.XBean;
import com.ioc.annotation.XInject;
import lombok.extern.log4j.Log4j2;

import java.util.List;
import java.util.stream.Stream;

/**
 * 根据注解自动注入bean
 *
 * @author SaErNuoSi
 * @date 2018/4/19 14:49
 */
@Log4j2
public final class AnnotationAutoInject {
    private static final DefaultIOC DEFAULT_IOC = new DefaultIOC();

    public void autoInject(Scanner scanner) {
        List<ClassDefine> classDefines = scanner.getClassDefines();
        /*先实例化所有的Xbean的注解,防止空指针*/
        classDefines.forEach(classDefine -> {
            Class<?> clazz = classDefine.getClazz();
            XBean xBean = clazz.getAnnotation(XBean.class);
            if (xBean != null) {
                log.info("XBean注解实例化对象: {}", clazz);
                DEFAULT_IOC.addBean(ReflectiveUtils.getInstance(clazz));
            }
        });
        /*给所有的Xinject自动注入bean*/
        classDefines.forEach(classDefine -> {
            Class<?> clazz = classDefine.getClazz();
            Stream.of(clazz.getDeclaredFields()).forEach(field -> {
                XInject xInject = field.getAnnotation(XInject.class);
                if (xInject != null) {
                    DefaultInject defaultInject = new DefaultInject(DEFAULT_IOC, field);
                    defaultInject.inject(DEFAULT_IOC.getBean(clazz));
                }
            });
        });
    }

    public static void main(String[] args) {
        AnnotationAutoInject annotationAutoInject = new AnnotationAutoInject();
        annotationAutoInject.autoInject(new Scanner("com.ioc"));
    }
}
